package com.chenl.provider.DEMOS.Caffeine的使用;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.chenl.provider.util.RedisService;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;


import com.google.common.cache.RemovalNotification;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/caffeine")
public class caffeineController {
    @Autowired
    RedisService redisService;
    LoadingCache<String, Object> cache = Caffeine.newBuilder()
            .expireAfterWrite(15, TimeUnit.SECONDS)
            .removalListener(new RemovalListener<String, Object>() {
                @Override
                public void onRemoval(@Nullable String key, @Nullable Object value, @NonNull RemovalCause cause) {
                    System.out.println("键值对不存在:"+key + "----" + value+"清理原因:"+cause);
                }
            })
            .build(key->createData(key));

    private  String createData(String key) {
        Object test = redisService.get(key);
        String value=test+":value";
        System.out.println("666:"+value);
        return value;
    }


    @PostMapping("/test")
    public String testPut(@RequestBody JSONObject jsonObject){
        cache.put(jsonObject.getString("key"),"我叫张三");
        return  "ok";
    }
    @PostMapping("/test2")
    public String testGet(@RequestBody JSONObject jsonObject){
        Object value = cache.get(jsonObject.getString("key"));
        System.out.println(value);
        return  "ok";
    }

    @PostMapping("/test3")
    public String testDel(@RequestBody JSONObject jsonObject){
        System.out.println("准备del");
        cache.invalidate(jsonObject.getString("key"));
        return  "ok";
    }

    @PostMapping("/test4")
    public String testgetAll(@RequestBody JSONObject jsonObject){
        Object key = cache.getIfPresent(jsonObject.getString("key"));
        System.out.println("testgetAll---:"+key);
        return  "ok";
    }

}
